﻿from django.http import HttpResponse
from django.utils import simplejson
from geography.models import L34Object, Place

def get_geography_object(request):
    obj_name = request.GET['obj_name'].lower().capitalize().encode("utf8")
    parent_name = request.GET.get('parent_name', None)
    if parent_name is not None and obj_name is not None:
        children={}
        i = 0
        for c in L34Object.get_objects_by_name(obj_name):
            i += 1
            l2_name = c[5]+' '+c[6] if c[5] is not None and c[6] is not None else ''
            children[i] = {'id': c[0], 'name': c[1]+' '+c[2], 'l1_name': c[3]+' '+c[4], 'l2_name': l2_name, 'l1_id': c[7], 'l2_id': c[8]}
    json = simplejson.dumps(children)
    return HttpResponse(json, mimetype='application/json')
    
def get_place(request):
    name = request.GET.get('obj_name').lower()
    if name is not None:
        places = {}
        i = 0
        for p in Place.objects.select_related().filter(name__istartswith=name).all():
            places[i] = {}
            places[i]['id'] = p.pk
            places[i]['name'] = p.name
            places[i]['type'] = p.place_type
            places[i]['street'] = p.street
            places[i]['house_num'] = p.house_num
            places[i]['apartament_num'] = p.apartament_num
            places[i]['l0'] = str(p.L0Object_id) if p.L0Object is not None else 'null'
            places[i]['l1'] = str(p.L1Object_id) if p.L1Object is not None else 'null'
            places[i]['l2'] = str(p.L2Object_id) if p.L2Object is not None else 'null'
            places[i]['l34'] = str(p.L34Object_id) if p.L34Object is not None else 'null'
            places[i]['l1_name'] = str(p.L1Object.name) if p.L1Object is not None else 'null'
            places[i]['l2_name'] = str(p.L2Object.name) if p.L2Object is not None else 'null'
            places[i]['l34_name'] = str(p.L34Object.name) if p.L34Object is not None else 'null'
            i += 1
    json = simplejson.dumps(places)
    return HttpResponse(json, mimetype='application/json')